package com.github.eclipseace.mybatis.entity.builder.xml;

import java.util.HashMap;
import java.util.Map;

import org.apache.ibatis.parsing.GenericTokenParser;
import org.apache.ibatis.parsing.TokenHandler;

import com.github.eclipseace.mybatis.util.StringUtils;

/**
 * @author eclipseAce
 */
public class VariableContext extends HashMap<String, String> {
	public static final String OPEN_TOKEN = "{{";
	public static final String CLOSE_TOKEN = "}}";

	private static final long serialVersionUID = 1L;

	private final GenericTokenParser tokenParser;

	public VariableContext() {
		this.tokenParser = createTokenParser();
	}

	public VariableContext(Map<? extends String, ? extends String> m) {
		super(m);
		this.tokenParser = createTokenParser();
	}

	protected GenericTokenParser createTokenParser() {
		return new GenericTokenParser(OPEN_TOKEN, CLOSE_TOKEN, new TokenHandler() {
			@Override
			public String handleToken(String content) {
				return StringUtils.emptyIfNull(get(content));
			}
		});
	}

	public VariableContext newContext() {
		return new VariableContext(this);
	}

	public void put(String prefix, String name, String value) {
		if (StringUtils.isNotEmpty(prefix)) {
			put(prefix + "." + name, value);
		} else {
			put(name, value);
		}
	}

	public String parseTokens(String text) {
		return tokenParser.parse(text);
	}
}
